package com.node.tools.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Created IntelliJ IDEA.
 * @Author XYoK
 * @PackageName com.node.tools.utils
 * @Description Http工具类
 * @Setting Editor | File and Code Templates.
 */
public class HttpUtil {
	/**
	 * HttpGet请求
	 * @param url     连接
	 * @param headers 请求头
	 * @param params  参数只支持String
	 * @return
	 * @throws Exception
	 */
	public static String sslGet(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
		String body = "";
		URIBuilder uriBuilder = new URIBuilder(url);
		Set<String> header = headers.keySet();
		Set<String> v = params.keySet();
		for (String key : v) {
			String vs = headers.get(key);
			uriBuilder.addParameter(key, vs);
		}
		//创建get方式请求对象
		HttpGet get = new HttpGet(uriBuilder.build());
		for (String key : header) {
			String vs = headers.get(key);
			get.setHeader(key, vs);
		}
		CloseableHttpResponse response = HttpClients.createDefault().execute(get);//执行请求操作，并拿到结果（同步阻塞）
		HttpEntity entity = response.getEntity();//获取结果实体
		if (entity != null) {
			body = EntityUtils.toString(entity, "UTF-8");//按指定编码转换结果实体为String类型
		}
		EntityUtils.consume(entity);
		response.close();//释放链接
		return body;
	}

	/***
	 * HttpPost请求
	 * @param url
	 * @param headers
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public static String sslPost(String url, Map<String, String> headers, List<BasicNameValuePair> list) throws Exception {
		HttpPost httpPost = new HttpPost(url);// 创建POST请求对象
		Set<String> head = headers.keySet();
		for (String key : head) {
			String vs = headers.get(key);
			httpPost.setHeader(key, vs);
		}
		//设置参数
		UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
		httpPost.setEntity(entityParam);
		CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
		HttpEntity entity = response.getEntity();
		String body = "";
		if (entity != null) {
			//按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, "UTF-8");
		}
		EntityUtils.consume(entity);
		response.close();
		return body;
	}

	/**
	 * 发送post请求
	 * @param url  路径
	 * @param params  参数(json类型)
	 * @param encoding 编码格式
	 * @return
	 * @throws Exception
	 */
	public static String sslJsonPost(String url, String params, String encoding, String token) throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();//创建httpclient对象
		HttpPost httpPost = new HttpPost(url);//创建post方式请求对象
		//装填参数
		StringEntity s = new StringEntity(params, "utf-8");
		s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		httpPost.setEntity(s);//设置参数到请求对象中
		//设置header信息
		//指定报文头【Content-type】、【User-Agent】
		httpPost.setHeader("Content-type", "application/json");
		httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		httpPost.setHeader("Authorization", "Bearer " + token);
		CloseableHttpResponse response = client.execute(httpPost);//执行请求操作，并拿到结果（同步阻塞）
		HttpEntity entity = response.getEntity();//获取结果实体
		String body = "";
		System.out.println("请求地址："+url);
		if (entity != null) {
			body = EntityUtils.toString(entity, encoding);//按指定编码转换结果实体为String类型
		}
		EntityUtils.consume(entity);
		response.close();//释放链接
		return body;
	}

	/**
	 * 发送GET请求
	 *
	 * @param url
	 *            目的地址
	 * @param parameters
	 *            请求参数，Map类型。
	 * @return 远程响应结果
	 */
	public static String sendGet(String url, Map<String, String> parameters) {
		String result = "";
		BufferedReader in = null;// 读取响应输入流
		StringBuffer sb = new StringBuffer();// 存储参数
		String params = "";// 编码之后的参数
		try {
			// 编码请求参数
			if (parameters.size() == 1) {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"));
				}
				params = sb.toString();
			} else {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8")).append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
			String full_url = url + "?" + params;
			System.out.println(full_url);
			// 创建URL对象
			java.net.URL connURL = new java.net.URL(full_url);
			// 打开URL连接(建立了一个与服务器的tcp连接,并没有实际发送http请求！)
			URLConnection urlConnection=connURL.openConnection();
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) urlConnection;
			// 设置通用请求属性(如果已存在具有该关键字的属性，则用新值改写其值。)
			httpConn.setRequestProperty("Accept", "*/*");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
			// 建立实际的连接(远程对象变为可用。远程对象的头字段和内容变为可访问)
			httpConn.connect();
			// 响应头部获取
			Map<String, List<String>> headers = httpConn.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : headers.keySet()) {
				System.out.println(key + "\t：\t" + headers.get(key));
			}
			// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}